<?php
namespace app\mingteng\controller;

use app\api\controller\Base;
use app\mingteng\logic\GoodsLogic;
use app\mingteng\logic\OrderLogic;
use think\AjaxPage;
use think\Page;
use think\Db;
use app\api\controller\Payment;

class Order extends Base {

    public $orderSubscribeStatus;
    public $orderCourseStatus;
    public $orderMotionStatus;
    public $orderFoodsStatus;
    public $listRows;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        $this->listRows = 20;
        $this->orderSubscribeStatus = C('orderSubscribeStatus');
        $this->assign('orderSubscribeStatus', $this->orderSubscribeStatus);
        $this->orderCourseStatus = C('orderCourseStatus');
        $this->assign('orderCourseStatus', $this->orderCourseStatus);
        $this->orderMotionStatus = C('orderMotionStatus');
        $this->assign('orderMotionStatus', $this->orderMotionStatus);
        $this->orderFoodsStatus = C('orderFoodsStatus');
        $this->assign('orderFoodsStatus', $this->orderFoodsStatus);

    }

    public function subscribe(){

        $subscribe_dai = Db::name('order_subscribe')->where('orderStatus',0)->select();
        $subscribe_yi = Db::name('order_subscribe')->where('orderStatus',1)->select();

        if($subscribe_dai){
            foreach($subscribe_dai as $v){
                $expireTime = $v['orderAddTime'] + 600;

                if(time()>=$expireTime){
                    $orderSubscribeId = $v['orderSubscribeId'];
                    Db::name('order_subscribe')->where('orderSubscribeId',$orderSubscribeId)->update(['orderStatus' => -1,'freeAmount'=>0]);
                }
            }
        }
        if($subscribe_yi){
            foreach($subscribe_yi as $v){
                $orderTimePeriodType = explode(',',$v['orderTimePeriodType']);
                $timePeriod = config('timePeriod')[max($orderTimePeriodType)-1];
                $time = strtotime(date('Y-m-d',$v['orderDate']).' '.$timePeriod['endTime']);
                if(time()>$time){
                   $orderSubscribeId = $v['orderSubscribeId'];
                   Db::name('order_subscribe')->where('orderSubscribeId',$orderSubscribeId)->update(['orderStatus' => 2]);
                }
            }
        }

        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $this->assign('shopList', $shopList);

        return $this->fetch();
    }

    public function ajax_subscribe(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['userName|userPhone'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['shopId']) && !empty($params['shopId'])) {
            $where['orderShopId'] = array('=', $params['shopId']);
        }
        if (isset($params['orderStatus']) && $params['orderStatus'] != '') {
            $where['orderStatus'] = array('=', $params['orderStatus']);
        }

        $count = Db::name('order_subscribe')->where($where)->count();
        $list = Db::name('order_subscribe')->where($where)->page($page, $this->listRows)
            ->order('orderAddTime desc')->select();
        foreach ($list as &$value){
            $value['shopName'] = Db::name('shop')->where('shopId', '=', $value['orderShopId'])->getField('shopName');
            $value['positionNo'] = Db::name('position')->where('positionId', '=', $value['orderPositionId'])->getField('positionNo');
        }

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();

        $this->assign('list', $list);
        $this->assign('page', $show);
        return $this->fetch();
    }

    public function course(){

        $order_course = Db::name('order_course')->where(['orderStatus'=>0,'source'=>0])->select();

        if($order_course){
            foreach($order_course as $v){
                $expireTime = $v['orderAddTime'] + 600;

                if(time()>=$expireTime){
                    $orderCourseId = $v['orderCourseId'];
                    Db::name('order_course')->where('orderCourseId',$orderCourseId)->update(['orderStatus' => -1]);
                }
            }
        }

        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $this->assign('shopList', $shopList);
        $coachList = Db::name('coachs')->where('coachIsDel', '=', '0')->select();
        $this->assign('coachList', $coachList);

        return $this->fetch();
    }

    public function ajax_course(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['orderCourseName'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['shopId']) && !empty($params['shopId'])) {
            $where['orderShopId'] = array('=', $params['shopId']);
        }
        if (isset($params['coachId']) && !empty($params['coachId'])) {
            $where['orderCoachId'] = array('=', $params['coachId']);
        }
        if (isset($params['orderStatus']) && $params['orderStatus'] != '') {
            $where['orderStatus'] = array('=', $params['orderStatus']);
        }

        $where['source'] = 0;
        $count = Db::name('order_course')->where($where)->count();
        $list = Db::name('order_course')->where($where)->page($page, $this->listRows)
            ->order('orderAddTime desc')->select();
        foreach ($list as &$value){
            $value['shopName'] = Db::name('shop')->where('shopId', '=', $value['orderShopId'])->getField('shopName');
            $user = Db::name('user')->where('userId', '=', $value['userId'])->find();
            $value['user'] = $user;
            $coach = Db::name('coachs')->where('coachId', '=', $value['orderCoachId'])->find();
            $value['coach'] = $coach;
        }

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();

        $this->assign('list', $list);
        $this->assign('page', $show);
        return $this->fetch();
    }

    public function getCourseDetail(){
        $orderId = input('orderId', '');

        $orderInfo = Db::name('order_course')->where('orderCourseId', '=', $orderId)->find();
        $orderInfo['user'] = Db::name('user')->where('userId', '=', $orderInfo['userId'])->find();
        $orderInfo['shop'] = Db::name('shop')->where('shopId', '=', $orderInfo['orderShopId'])->find();
        $orderInfo['coach'] = Db::name('coachs')->where('coachId', '=', $orderInfo['orderCoachId'])->find();
        $evaluation = Db::name('coach_course_evaluation')->where('orderEvaluationId', '=', 'orderEvaluationId')->find();
        $orderInfo['orderEvaluationId'] > 0 ? $orderInfo['evaluation'] = $evaluation : $orderInfo['evaluation'] = array();
        !empty($orderInfo['evaluation']) ? $orderEvaluationImages = explode(',', $evaluation['orderEvaluationImages']) : $orderEvaluationImages = "";

        $orderLog = Db::name('order_course_log')->where('orderCourseId', '=', $orderInfo['orderCourseId'])->order('logAddTime desc')->select();

        $this->assign('orderLog', $orderLog);
        $this->assign('orderInfo', $orderInfo);
        $this->assign('orderEvaluationImages', $orderEvaluationImages);
        return $this->fetch('course_detail');
    }

    public function doOrderCourseStatus(){
        $orderId = input('orderId', '');
        Db::name('order_course')->where('orderCourseId', '=', $orderId)->save(array('orderStatus' => 2));
        return json(array("code" => 200, "msg" => "操作成功"));
    }

    public function orderCourseNote(){
        $orderId = input('orderId', '');
        $this->assign('orderCourseId', $orderId);

        $orderLog = Db::name('order_course_log')->where('orderCourseId', '=', $orderId)->order('logAddTime desc')->select();
        $this->assign('orderLog', $orderLog);

        return $this->fetch('course_note_add');
    }

    public function doOrderCourseNote(){
        $params = input('post.');

        if (empty($params['content'])) {
            return json(array('code' => 500, 'msg' => '请输入内容'));
        }
        $admin_id = session('admin_id');
        $adminInfo = Db::name('admin')->where('admin_id', '=', $admin_id)->find();
        Db::name('order_course_log')->insert(array(
            'orderCourseId' => $params['orderCourseId'],
            'logAddTime' => time(),
            'logName' => $adminInfo['user_name'],
            'logContent' => $params['content']
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function delOrderCourseLog(){
        $del_id = input('del_id');

        Db::name('order_course_log')->where('orderCourseLogId', '=', $del_id)->delete();
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function motion(){
        return $this->fetch();
    }

    public function ajax_motion(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['orderMotionNo|orderTransactionId'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['orderType']) && $params['orderType'] != '') {
            $where['orderType'] = array('=', $params['orderType']);
        }
        if (isset($params['orderStatus']) && $params['orderStatus'] != '') {
            $where['orderStatus'] = array('=', $params['orderStatus']);
        }
        $motion = Db::name('order_motion')->where($where)->select();
        foreach ($motion as $v){
            if($v['orderStatus'] == 0){
                if(time() >= $v['orderAddTime'] + 600){
                    Db::name('order_motion')->where('orderMotionId',$v['orderMotionId'])->update(['orderStatus'=>'-1']);
                }
            }
        }
        $count = Db::name('order_motion')->where($where)->count();
        $list = Db::name('order_motion')->where($where)->page($page, $this->listRows)
            ->order('orderAddTime desc')->select();
        foreach ($list as &$value){
            $user = Db::name('user')->where('userId', '=', $value['userId'])->find();
            $value['user'] = $user;

        }

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();

        $this->assign('list', $list);
        $this->assign('page', $show);
        return $this->fetch();
    }

    public function getMotionDetail(){
        $orderId = input('orderId', '');

        $orderInfo = Db::name('order_motion')->where('orderMotionId', '=', $orderId)->find();
        $orderInfo['user'] = Db::name('user')->where('userId', '=', $orderInfo['userId'])->find();
        $this->assign('orderInfo', $orderInfo);

        $orderGoods = Db::name('order_motion_goods')->where('order_id', '=', $orderInfo['orderMotionId'])->select();
        $this->assign('orderGoods', $orderGoods);

        return $this->fetch('motion_detail');
    }

    public function doOrderMotionStatus(){
        $params = input('post.');

        Db::name('order_motion')->where('orderMotionId', '=', $params['orderId'])->save(array(
            'orderStatus' => 2,
            'orderAdminNote' => !empty($params['orderAdminNote']) ? $params['orderAdminNote'] : "",
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function foods(){
        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $this->assign('shopList', $shopList);

        return $this->fetch();
    }

    public function ajax_foods(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['orderMotionNo|orderTransactionId'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['shopId']) && $params['shopId'] != '') {
            $where['orderShopId'] = array('=', $params['shopId']);
        }
        if (isset($params['orderStatus']) && $params['orderStatus'] != '') {
            $where['orderStatus'] = array('=', $params['orderStatus']);
        }

        $count = Db::name('order_foods')->where($where)->count();
        $list = Db::name('order_foods')->where($where)->page($page, $this->listRows)
            ->order('orderAddTime desc')->select();
        foreach ($list as &$value){
            $user = Db::name('user')->where('userId', '=', $value['userId'])->find();
            $value['user'] = $user;
            $shop = Db::name('shop')->where('shopId', '=', $value['orderShopId'])->find();
            $value['shop'] = $shop;
        }

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();

        $this->assign('list', $list);
        $this->assign('page', $show);
        return $this->fetch();
    }


    public function getFoodsDetail(){
        $orderId = input('orderId', '');

        $orderInfo = Db::name('order_foods')->where('orderFoodsId', '=', $orderId)->find();
        $orderInfo['user'] = Db::name('user')->where('userId', '=', $orderInfo['userId'])->find();
        $orderInfo['shop'] = Db::name('shop')->where('shopId', '=', $orderInfo['orderShopId'])->find();
        $this->assign('orderInfo', $orderInfo);

        $orderGoods = Db::name('order_foods_goods')->where('order_id', '=', $orderInfo['orderFoodsId'])->select();
        $this->assign('orderGoods', $orderGoods);

        return $this->fetch('foods_detail');
    }

    public function doOrderFoodsStatus(){
        $params = input('post.');

        Db::name('order_foods')->where('orderMotionId', '=', $params['orderId'])->save(array(
            'orderStatus' => 2,
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

//    public function export_order(){
//    	//搜索条件
//        $group_id =  I('group_id');
//		$order_status = I('order_status');
//        $order_sn = I('order_sn');
//        $timegap = I('timegap');
//        $where = array();//搜索条件
//
//        if($group_id){
//            $where['group_id'] = $group_id;
//        }
//        if($order_status){
//            $where['order_status'] = $order_status;
//        }
//        if($order_sn){
//            $where['order_sn'] = $order_sn;
//        }
//
//        if($timegap){
//            $gap = explode('-', $timegap);
//            $begin = strtotime($gap[0]);
//            $end = strtotime($gap[1]);
//            $where['add_time'] = ['between',[$begin, $end]];
//        }
//
//
//        $orderList = Db::name('order')->field("*,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time")->where($where)->order('order_id')->select();
//		foreach($orderList as $k=>$val){
//			$orderList[$k]['user_name'] = M('user')->where('user_id='.$orderList[$k]['user_id'])->getField('user_name');
//			$orderList[$k]['group_name'] = M('groups')->where('group_id='.$orderList[$k]['group_id'])->getField('group_name');
//		}
//    	$strTable ='<table width="500" border="1">';
//    	$strTable .= '<tr>';
//    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">编号</td>';
//    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
//    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
//		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">金额</td>';
//		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">名称</td>';
//        $strTable .= '<td style="text-align:center;font-size:12px;" width="400px">数量</td>';
//    	$strTable .= '</tr>';
//
//	    if(is_array($orderList)){
//	    	foreach($orderList as $k=>$val){
//
//	    		$strTable .= '<tr>';
//	    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
//	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['add_time']).' </td>';
//	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['user_name'].' </td>';
//	    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].' </td>';
//
//	    		$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
//	    		$strGoods="";
//                $goods_num = 0;
//	    		foreach($orderGoods as $goods){
//                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$goods['goods_name'].' </td>';
//                    $strTable .= '<td style="text-align:left;font-size:12px;">'.$goods['goods_num'].' </td>';
//
//	    		}
//	    		unset($orderGoods);
//                //$strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
//
//	    		$strTable .= '</tr>';
//	    	}
//	    }
//
//    	$strTable .='</table>';
//    	unset($orderList);
//    	downloadExcel($strTable,'订单');
//    	exit();
//    }


    /*
     *充值订单首页
     */
    public function up_index(){
        $begin = date('Y/m/d',strtotime("-1 months"));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
    }

    public function ajax_up_index(){
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $order_sn = I('order_sn','','trim');
        $order_sn ? $condition['transaction_id'] = ['like',"%$order_sn%"] : false;
        I('order_status') != '' ? $condition['status'] = I('order_status') : false;
        $count = M('recharge')->where($condition)->count();
        $Page  = new AjaxPage($count,15);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if($key == 'add_time'){
                $between_time = explode(',',$val[1]);
                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
                $Page->parameter['timegap'] = $parameter_add_time;
            }
        }
        $show = $Page->show();

        //获取订单列表
        $orderList = M('recharge')->where($condition)->limit("$Page->firstRow,$Page->listRows")->order('add_time desc')->select();;
        foreach ($orderList as $k=>$v){
            $orderList[$k]['username'] = M('user')->where(array('user_id' => $v['user_id']))->getField('username');
            $orderList[$k]['phone'] = M('user')->where(array('user_id' => $v['user_id']))->getField('phone');
        }
        //dump($orderList);die;
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }




    //商场订单
    public function shop_index(){
        $begin = date('Y/m/d',strtotime("-1 months"));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('shop_order_status',C('shop_order_status'));
        $this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
    }

    public function ajax_shop_index(){

        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();

        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;

        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('shop_order')->where($condition)->count();
        $Page  = new AjaxPage($count,15);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if($key == 'add_time'){
                $between_time = explode(',',$val[1]);
                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
                $Page->parameter['timegap'] = $parameter_add_time;
            }
        }
        $show = $Page->show();
        //获取订单列表
        $orderList = M('shop_order')->where($condition)->limit("$Page->firstRow,$Page->listRows")->order('add_time desc')->select();;
        foreach ($orderList as $k=>$v){
            $orderList[$k]['goods_count'] = M('order_goods')->where('order_id='.$orderList[$k]['order_id'])->count();
        }
        //dump($orderList);exit;
        $this->assign('shop_order_status',C('shop_order_status'));
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }


    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);

        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order['order_status']);
        $order['user'] = M('user')->where(['user_id'=>$order['user_id']])->find();
       
        $this->assign('order',$order);
        $this->assign('orderGoods',$orderGoods);
        $split = count($orderGoods) >1 ? 1 : 0;
        foreach ($orderGoods as $val){
            if($val['goods_num']>1){
                $split = 1;
            }
        }
        $this->assign('shop_order_status',C('shop_order_status'));
        $this->assign('split',$split);
        $this->assign('button',$button);
        return $this->fetch();
    }

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){
        $orderLogic = new OrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');
        if($action && $order_id){
            $a = $orderLogic->orderProcessHandle($order_id,$action);
            if($a !== false){
                ajaxReturn(array('status' => 1, 'msg' => '操作成功', 'data' => array('result' => U('order/index'))));
            }else{
                if ($action == 'remove') {
                    ajaxReturn(array('status' => 0, 'msg' => '操作失败', 'data' => array('result' => U('order/index'))));
                }
                ajaxReturn(array('status' => 0,'msg' => '操作失败'));
            }
        }else{
            $this->error('参数错误',U('Order/detail',array('order_id'=>$order_id)));
        }
    }


    /*
     * 点餐订单首页
     */
    public function meal_index(){
        $begin = date('Y/m/d',strtotime("-1 months"));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('timegap',$begin.'-'.$end);
        return $this->fetch();
    }

    public function ajax_meal_index(){
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $order_sn = I('order_sn','','trim');
        $order_sn ? $condition['order_sn|transaction_id'] = ['like',"%$order_sn%"] : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        $count = M('meal_order')->where($condition)->count();
        $Page  = new AjaxPage($count,15);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if($key == 'add_time'){
                $between_time = explode(',',$val[1]);
                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
                $Page->parameter['timegap'] = $parameter_add_time;
            }
        }
        $show = $Page->show();
        //获取订单列表
        $orderList = M('meal_order')->where($condition)->limit("$Page->firstRow,$Page->listRows")->order('add_time desc')->select();;
        foreach ($orderList as $k=>$v){
            $orderList[$k]['phone'] = M('user')->where(array('user_id' => $v['user_id']))->getField('phone');
            $orderList[$k]['order_goods'] = M('meal_order_goods')->where(array('order_id' => $v['order_id']))->select();
        }
        //dump($orderList);die;
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }


	//取消订单
	public function cancel_order(){
		$order_id = I('param.id');
		$order = M('order')->where(array('order_sn' =>$order_id))->find();
		if ($order['order_status'] != 1){
			ajaxReturn(array('status' => 500,'msg' => '订单状态不符合'));
		}
		if ($order['order_status'] == 1){
            $time1 = date('Y-m-d H:i',$order['subscribe_time']); //当前时间
            $last_time = strtotime(date("Y-m-d H:i",strtotime("-2 hour",strtotime($time1))));
            if (time() > $last_time){
                if (time() < $order['subscribe_time']){
                    $order['refund_fee'] = round($order['goods_price'] * 0.8,2);
                    $result = $this->payment->payment_refund($order);
                    if ($result['result_code'] == 'SUCCESS'){
                        M('order')->where(array('order_sn' =>$order['order_sn']))->save(array('order_status' => -1));
                        ajaxReturn(array('status' => 200,'msg' => '取消成功，退款中','url' => U('order/index')));
                    }else{
                        ajaxReturn(array('status' => 500,'msg' => $result['err_code_des']));
                    }
                }else{
                    ajaxReturn(array('status' => 500,'msg' => '已超过预约时间无法取消'));
                }
            }else{
                $order['refund_fee'] = $order['goods_price'];
                $result = $this->payment->payment_refund($order);
                if ($result['result_code'] == 'SUCCESS'){
                    M('order')->where(array('order_sn' =>$order['order_sn']))->save(array('order_status' => -1));
                    ajaxReturn(array('status' => 200,'msg' => '退款成功','url' => U('order/index')));
                }else{
                    ajaxReturn(array('status' => 500,'msg' => $result['err_code_des']));
                }
            }
		}
	}

    /**
     * 取消预约订单页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancel_reservation_order(){
        $order_id = I('param.orderId');
        if(empty($order_id)){
            ajaxReturn(array('status' => 0, 'msg' => '参数错误'));
        }

        $subscribe= Db::name('order_subscribe')->where('orderSubscribeId',$order_id)->find();
        $timePeriodType = explode(',', $subscribe['orderTimePeriodType']);

        $data=[];
        foreach($timePeriodType as $k=>$v){
            $data[$k]['type'] = $v;
            $data[$k]['data'] = config('timePeriod')[$v-1]['startTime'].'-'.config('timePeriod')[$v-1]['endTime'];

        }
        $this->assign('order_id',$order_id);
        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 分段取消订单
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function doCancel(){

        $params = input();
        $orderId = $params['order_id'];  //订单id
        $timePeriodType = $params['type']; //时间段标识

        if(empty($orderId)){
            return json(array('code' => 500, 'msg' => '订单id不能为空'));
        }
        foreach ($timePeriodType as $v){
            $this->doCancels($orderId,$v);
        }

        return json(array('code' => 200, 'msg' => '成功'));
    }

    public function doCancels($orderId,$timePeriodType){

        $orderInfo = Db::name('order_subscribe')
            ->where('orderSubscribeId', '=', $orderId)
            ->find();

        $userInfo = Db::name('user')->where('userId',$orderInfo['userId'])->find();

        if ($orderInfo['orderStatus'] == '-1' || $orderInfo['orderStatus'] == '2') {
            return json(array('code' => 500, 'msg' => '订单状态错误'));
        }
        $orderStartTime = config('timePeriod')[$timePeriodType-1];
        $orderTimePeriodType = explode(',',$orderInfo['orderTimePeriodType']);
        $min =  min($orderTimePeriodType);
        $newOrderTimePeriodType = $orderInfo['orderTimePeriodTypeLog'];
        $orderTimePeriodTypeAyy = explode(',',$newOrderTimePeriodType);

        //判断订单是存在免费并且当前时间段就是免费时间段
        if($orderInfo['freeAmount'] !=0  && $timePeriodType == $min){
            //免费时间段
            Db::startTrans();

            try {

                $catchBalance = array(
                    'userId' => $userInfo['userId'],
                    'balanceAmount' => 0,
                    'addTime' => time(),
                    'balanceNote' => '预约订单:' . $orderInfo['orderSubscribeNo'] . ',时间段:' . $orderStartTime['startTime'] . '-' . $orderStartTime['endTime'] . ",取消退款",
                    'sourceNote' => '球场球位预约订单退款',
                );
                Db::name('user_balance_log')->insertGetId($catchBalance);

                Db::name('user')->where('userId', '=', $userInfo['userId'])->setDec('userIntegral', 0);
                $catchIntegral = array(
                    'userId' => $userInfo['userId'],
                    'integralAmount' => "-" . 0,
                    'addTime' => time(),
                    'integralNote' => '预约订单：' . $orderInfo['orderSubscribeNo'] . ',时间段:' . $orderStartTime['startTime'] . '-' . $orderStartTime['endTime'] . ",取消积分退回",
                    'sourceNote' => '球场球位预约取消-退回积分',
                );
                Db::name('user_integral_log')->insertGetId($catchIntegral);

                $order_subscribe_fen = array(

                    'orderSubscribeId' => $orderId,
                    'orderTimePeriodType' => $timePeriodType,
                    'orderPayName' => '免费',
                    'cancelTime' => time(),
                    'orderRefundPrice' => 0,
                );
                $subscribe_fen = Db::name('order_subscribe_fen')->where(['orderSubscribeId' => $orderId, 'orderTimePeriodType' => $timePeriodType])->find();
                if($subscribe_fen){
                    return json(array('code' => 500, 'msg' => '订单已取消,操作失败'));
                }

                Db::name('order_subscribe_fen')->insert($order_subscribe_fen);

                $memberTimeType = explode(',',$orderInfo['memberTimeType']);
                if(in_array($timePeriodType,$memberTimeType)){
                    $memberTimeType = array_diff($memberTimeType,[$timePeriodType]);
                }

                $count = Db::name('order_subscribe_fen')->where('orderSubscribeId',$orderId)->count();

                if(count($orderTimePeriodTypeAyy) == $count){

                    Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                        'orderStatus' => '-1',
                        'orderRefundPrice' => $orderInfo['orderRefundPrice'] + 0,
                        'orderRefundNo' => 'YYTK' . date('Ymd', time()) . $userInfo['userId'] . rand(1000, 9999),
                        'freeAmount' => 0,
                        'orderTimePeriodType'=>$newOrderTimePeriodType,
                        'memberTimeType'=>implode(',',$memberTimeType),
                    ));
                }else{

                    $add = [];
                    foreach($orderTimePeriodType as $v){
                        if($v != $timePeriodType){
                            $add[] = $v;
                        }
                    }
                    Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                        'orderTimePeriodType'=>implode(',',$add),
                        'freeAmount'=>0,
                        'memberTimeType'=>implode(',',$memberTimeType),
                    ));
                }

                (new Payment())->unsubscribeSms($orderInfo,$orderStartTime);

                Db::commit();

                return json(array('code' => 200, 'msg' => '取消成功'));
            } catch (\Exception $exception) {

                Db::rollback();
                return json(array('code' => 500, 'msg' => $exception->getMessage()));
            }

        }else{

            if($orderInfo['orderPayName'] == '余额支付' || $orderInfo['orderPayName'] == 'balance'){

                $positionPrice = (new Payment())->positionPrice($userInfo,$orderInfo,$timePeriodType);

                Db::startTrans();

                try {

                    Db::name('user')->where('userId', '=', $userInfo['userId'])->setInc('userBalance', $positionPrice);


                    $catchBalance = array(
                        'userId' => $userInfo['userId'],
                        'balanceAmount' => $positionPrice,
                        'addTime' => time(),
                        'balanceNote' => '预约订单:' . $orderInfo['orderSubscribeNo'] . ',时间段:' . $orderStartTime['startTime'] . '-' . $orderStartTime['endTime']. ",取消退款",
                        'sourceNote' => '球场球位预约订单退款',
                    );
                    Db::name('user_balance_log')->insertGetId($catchBalance);
                    $orderIntegralPrice = round($positionPrice * (new Payment())->integralConfig['integralConfig'], 2);
                    Db::name('user')->where('userId', '=', $userInfo['userId'])->setDec('userIntegral', $orderIntegralPrice);
                    //分销上级扣除积分
                    $superior = new Payment();
                    $superior->superiorIntegralDec($orderInfo['userId'],$orderIntegralPrice);

                    $catchIntegral = array(
                        'userId' => $userInfo['userId'],
                        'integralAmount' => "-" . $orderIntegralPrice,
                        'addTime' => time(),
                        'integralNote' => '预约订单：' . $orderInfo['orderSubscribeNo']. ',时间段:' . $orderStartTime['startTime'] . '-' . $orderStartTime['endTime'] . ",取消积分退回",
                        'sourceNote' => '球场球位预约取消-退回积分',
                    );
                    Db::name('user_integral_log')->insertGetId($catchIntegral);

                    $order_subscribe_fen = array(

                        'orderSubscribeId' => $orderId,
                        'orderTimePeriodType' => $timePeriodType,
                        'orderPayName' => '余额支付',
                        'cancelTime' => time(),
                        'orderRefundPrice' => $positionPrice,
                    );
                    $subscribe_fen = Db::name('order_subscribe_fen')->where(['orderSubscribeId' => $orderId, 'orderTimePeriodType' => $timePeriodType])->find();
                    if($subscribe_fen){
                        return json(array('code' => 500, 'msg' => '订单已取消,操作失败'));
                    }

                    Db::name('order_subscribe_fen')->insert($order_subscribe_fen);

                    $memberTimeType = explode(',',$orderInfo['memberTimeType']);
                    if(in_array($timePeriodType,$memberTimeType)){
                        $memberTimeType = array_diff($memberTimeType,[$timePeriodType]);
                    }

                    $count = Db::name('order_subscribe_fen')->where('orderSubscribeId',$orderId)->count();

                    if(count($orderTimePeriodTypeAyy) == $count) {
                        Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                            'orderStatus' => '-1',
                            'orderRefundPrice' => $positionPrice + $orderInfo['orderRefundPrice'],
                            'orderRefundNo' => 'YYTK' . date('Ymd', time()) . $userInfo['userId'] . rand(1000, 9999),
                            'freeAmount' => 0,
                            'orderTimePeriodType'=>$newOrderTimePeriodType,
                            'memberTimeType'=>implode(',',$memberTimeType),
                        ));
                    }else{

                        $add = [];
                        foreach($orderTimePeriodType as $v){
                            if($v != $timePeriodType){
                                $add[] = $v;
                            }
                        }
                        Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                            'orderRefundPrice' => $positionPrice + $orderInfo['orderRefundPrice'],
                            'orderTimePeriodType'=>implode(',',$add),
                            'memberTimeType'=>implode(',',$memberTimeType),
                        ));
                    }
                    (new Payment())->unsubscribeSms($orderInfo,$orderStartTime);
                    Db::commit();

                    return json(array('code' => 200, 'msg' => '取消成功'));

                } catch (\Exception $exception) {

                    Db::rollback();
                    return json(array('code' => 500, 'msg' => $exception->getMessage()));
                }
            }elseif($orderInfo['orderPayName'] == '微信支付') {

                $positionPrice = (new Payment())->positionPrice($userInfo,$orderInfo,$timePeriodType);
                $orderInfo['orderRefundNo'] = 'YYTK' . date('Ymd', time()) . $userInfo['userId'] . rand(1000, 9999);
                $orderInfo['orderRefundPrice'] = $positionPrice;
                $orderInfo['orderActualPrice'] = $positionPrice;
                $res = (new Payment())->payment->paymentRefund($orderInfo);
                if ($res['return_code'] == "SUCCESS") {

                    $orderIntegralPrice = round($positionPrice * (new Payment())->integralConfig['integralConfig'], 2);
                    Db::name('user')->where('userId', '=', $orderInfo['userId'])->setDec('userIntegral', $orderIntegralPrice);
                    //分销上级扣除积分
                    $superior = new Payment();
                    $superior->superiorIntegralDec($orderInfo['userId'],$orderIntegralPrice);

                    $catchIntegral = array(
                        'userId' => $orderInfo['userId'],
                        'integralAmount' => "-" . $orderIntegralPrice,
                        'addTime' => time(),
                        'integralNote' => '预约订单：' . $orderInfo['orderSubscribeNo'] . ',时间段:' . $orderStartTime['startTime'] . '-' . $orderStartTime['endTime']. ",取消积分退回",
                        'sourceNote' => '球场球位预约取消-退回积分',
                    );
                    Db::name('user_integral_log')->insertGetId($catchIntegral);

                    $order_subscribe_fen = array(

                        'orderSubscribeId' => $orderId,
                        'orderTimePeriodType' => $timePeriodType,
                        'orderPayName' => '微信支付',
                        'cancelTime' => time(),
                        'orderRefundPrice' => $res['refund_fee'] / 100,
                        'orderRefundNo' => $res['out_refund_no'],
                    );
                    $subscribe_fen = Db::name('order_subscribe_fen')->where(['orderSubscribeId' => $orderId, 'orderTimePeriodType' => $timePeriodType])->find();
                    if($subscribe_fen){
                        return json(array('code' => 500, 'msg' => '订单已取消,操作失败'));
                    }

                    Db::name('order_subscribe_fen')->insert($order_subscribe_fen);

                    $memberTimeType = explode(',',$orderInfo['memberTimeType']);
                    if(in_array($timePeriodType,$memberTimeType)){
                        $memberTimeType = array_diff($memberTimeType,[$timePeriodType]);
                    }

                    $count = Db::name('order_subscribe_fen')->where('orderSubscribeId',$orderId)->count();

                    if(count($orderTimePeriodTypeAyy) == $count) {
                        Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                            'orderStatus' => '-1',
                            'orderRefundPrice' => $positionPrice + ($res['refund_fee'] / 100),
                            'orderRefundNo' => $res['out_refund_no'],
                            'orderRefundId' => $res['refund_id'],
                            'freeAmount' => 0,
                            'orderTimePeriodType'=>$newOrderTimePeriodType,
                            'memberTimeType'=>implode(',',$memberTimeType),
                        ));
                    }else{

                        $add = [];
                        foreach($orderTimePeriodType as $v){
                            if($v != $timePeriodType){
                                $add[] = $v;
                            }
                        }
                        Db::name('order_subscribe')->where('orderSubscribeId', '=', $orderInfo['orderSubscribeId'])->save(array(
                            'orderRefundPrice' => $positionPrice + ($res['refund_fee'] / 100),
                            'orderTimePeriodType'=>implode(',',$add),
                            'memberTimeType'=>implode(',',$memberTimeType),
                        ));
                    }
                    (new Payment())->unsubscribeSms($orderInfo,$orderStartTime);
                    return json(array('code' => 200, 'msg' => '取消成功'));
                }else{
                    return json(array('code' => 500, 'msg' => $res['return_msg']));
                }
            }
        }
    }

}
